
/*
 *    Copyright (C) 2016 Tamic
 *
 *    link :https://github.com/Tamicer/Novate
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.lch.base.http.interceptor;

import android.content.Context;
import android.text.TextUtils;

import com.lch.base.http.config.CacheProvide;
import com.lch.base.http.utils.NetworkUtil;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 网络请求缓存拦截器Cache-Control
 *
 * @author lee(29487113@qq.com) on 18/2/4
 */
public class CacheInterceptor implements Interceptor {
    Context mContext;

    public CacheInterceptor(Context context) {
        mContext = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String cacheString = request.header(CacheProvide.CACHE_TIME);
        if (TextUtils.isEmpty(cacheString)) {
            return chain.proceed(request);
        }


        int cacheTime = 0;
        try {
            cacheTime = Integer.parseInt(cacheString);
        } catch (NumberFormatException e) {

        }

        int maxAge = 0;
        int maxStale = 0;
        if (cacheTime > 0) {
            maxAge = cacheTime;
            maxStale = cacheTime;
        }

        if (NetworkUtil.isNetworkAvailable(mContext)) {
            Response response = chain.proceed(request);
            return response.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", "public, max-age=" + maxAge)
                    .build();
        } else {
            //没网络的时间 经过测试会跟有网络的时间叠加  例如有网络设置20秒 无网络设置20秒。第一次有网络，然后断开 最后一次 需要40秒
            //需要强行自定义 修改时间 如果用系统的 是无限大 导致不生效
            //https://www.jianshu.com/p/5cd7e95c2f29
            CacheControl FORCE_CACHE = new CacheControl.Builder()
                    .onlyIfCached()
                    .maxStale(maxStale, TimeUnit.SECONDS)
                    .build();

            //无网络时强制使用缓存数据
            request = request.newBuilder()
                    .cacheControl(FORCE_CACHE)
                    .build();
            Response response = chain.proceed(request);
            return response.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .build();
        }
    }
}
